package com.xiaojimao.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.xaiojimao.gr_common.CommonEnum.BizCommonEnum;
import com.xaiojimao.gr_common.exception.CommonException;
import com.xiaojimao.Service.SensitiveWordsService;
import com.xiaojimao.Utils.SensitiveWordsPerConfig;
import com.xiaojimao.Vo.SensitiveRequestParams;
import com.xiaojimao.Vo.SensitiveVo;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SensitiveWordsServiceImpl implements SensitiveWordsService {

    @Autowired
    SensitiveWordsPerConfig sensitiveWordsPerConfig;

    public SensitiveVo checkWords(String words) {
        // 初始化检查结果对象
        SensitiveVo sensitiveVo = null;
        // 构建检查请求参数对象
        SensitiveRequestParams params = new SensitiveRequestParams();
        // 设置key
        params.setColaKey(sensitiveWordsPerConfig.getColaKey());
        // 设置检查的值
        params.setWordStr(words);
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            String jsonString = JSON.toJSONString(params);
            String replace = jsonString.replace("c", "C");
            RequestBody body = RequestBody.create(mediaType, replace);
            Request request = new Request.Builder()
                    .url("https://luckycola.com.cn/tools/sensiWords")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Cookie", "lucyColaSession=s%3AN4wWz_lBWxS4PcQjx_pMaSZ77FOcQV47.WjFQ%2F7lHg9vS4%2BLa0oI89EEnQOsQ9EBs2blzh%2Fh9g%2B0")
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            sensitiveVo = JSON.parseObject(string, SensitiveVo.class);

            if (sensitiveVo == null) {
                throw new CommonException(BizCommonEnum.SYSTEM_CHECK_WORD_ERROR.getCode(), BizCommonEnum.SYSTEM_CHECK_WORD_ERROR.getMsg());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sensitiveVo;
    }

}
